package _02_链表;

import _05_二叉树.TreeNode;

/**
 * https://leetcode-cn.com/problems/merge-two-sorted-lists/
 * @Author: haogege
 * @Date: 2021/9/5
 */
public class _21_合并两个有序链表 {

    // 对于递归算法，较小的节点合并在较大的节点上
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null) return l2;
        if (l2 == null) return l1;

        if (l1.val > l2.val) {
           l2.next = mergeTwoLists(l1, l2.next);
           return l2;
        } else {
            l1.next = mergeTwoLists(l1.next, l2);
            return l1;
        }
    }

    // 迭代
    public ListNode mergeTwoLists1(ListNode l1, ListNode l2) {
        // 创建虚拟头结点
        ListNode node = new ListNode(0);
        // 指向当前节点
        ListNode cur = node;
        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                cur.next = l1;
                l1 = l1.next;
            } else {
                cur.next = l2;
                l2 = l2.next;
            }
            cur = cur.next;
        }
        if (l1 == null) {
            cur.next = l2;
        } else {
            cur.next = l1;
        }
        return node.next;
    }

}
